package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
@RequiredArgsConstructor
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //检查是不是白名单
        String path = exchange.getRequest().getURI().getPath();
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            boolean match = antPathMatcher.match(excludePath, path);
            //白名单，直接放行
            if (match) {
                return chain.filter(exchange);
            }
        }
        //解析jwt是否有效
        String token = exchange.getRequest().getHeaders().getFirst("authorization");
        if (token == null) {
            exchange.getResponse().setRawStatusCode(401);
            return exchange.getResponse().setComplete();
        }
        //解析jwt中的用户信息
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            exchange.getResponse().setRawStatusCode(401);
            return exchange.getResponse().setComplete();
        }

        //保存用户信息到请求头
        log.info("userId = {}", userId);
//        ServerHttpRequest newRequest = exchange.getRequest().mutate().header("user-info", userId.toString()).build();
//        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        exchange.getRequest()
                //获取可变构建器
                .mutate()
                //添加/覆盖请求头
                .header("user-info", userId.toString());
        //转发请求到微服务
        //放行
        //return chain.filter(newExchange);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
